#include <iostream>
using namespace std;
#include <pthread.h>
#include <string>
#include <mutex>
#include <condition_variable>
#include <unistd.h>
#include <vector>

int tickets = 1000;

class Thread_data
{
public:
    Thread_data(){
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_cond,nullptr);

    }
public:
    pthread_t tid;
    string name;
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
};

void *start_routine(void *args)
{
    Thread_data* ret  = static_cast<Thread_data*>(args);

    while (1)
    {
        pthread_mutex_lock(&ret->_lock);
        pthread_cond_wait(&ret->_cond,&ret->_lock);
        if (tickets > 0)
        {
            usleep(1234);
            cout << ret->name << "正在抢票：" << tickets << endl;
            tickets--;
            pthread_mutex_unlock(&ret->_lock);
        }
        else
        {       
            pthread_mutex_unlock(&ret->_lock);

            break;
        }
    }
    return nullptr;
}

int main()
{
    vector<Thread_data> tds(5);
    for (int i = 0; i < 5; i++)
    {
        Thread_data *ret = new Thread_data();
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "thread:%d", i + 1);

        ret->name += buffer;

        pthread_create(&tds[i].tid, nullptr, start_routine, (void *)ret);
    }

    for (auto e : tds)
    {
        sleep(1);
        pthread_join(e.tid, nullptr);
    }

    return 0;
}